#include <iostream>
#include <string>
#include <sys/types.h>        
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>


//c++11新特性“枚举类”
enum class Status
{
    NEW,        //新建客户端,
    CONNECTING,  //正在连接状态
    CONNECTED,  //已经连接
    DISCONNECTED,//断连
    CLOSED     //关闭客户端
};


class ClientConnection
{
public:
    ClientConnection(uint16_t port,const std::string& ip)
    :_sockfd(-1),
    _port(port),
    _ip(ip),
    _retry_interval(1),
    _max_retries(5),
    _status(Status::NEW)
    {}

     void DisConnect()
    {
        //断连函数
        if(_sockfd!=-1)
        {
            close(_sockfd);
            _status = Status::CLOSED;
            return;
        }
    }


    void Connect()
    {
        //1.创建sockfd
        _sockfd = socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd<0)
        {
            std::cerr<<"socket error"<<std::endl;
            exit(1);
        }
        //2.connect
        struct sockaddr_in server;                  
        memset(&server,0,sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        inet_pton(AF_INET,_ip.c_str(),&server.sin_addr);

        int n = connect(_sockfd,(struct sockaddr*)&server,sizeof(server));
        if(n<0)
        {
            //如果连接失败，需要把sockfd关闭
            DisConnect();
            _status = Status::DISCONNECTED;
            return;
        }

        _status = Status::CONNECTED;
    }

    int SockFd()
    {
        return _sockfd;
    }

    void ReConnect()
    {
        _status = Status::CONNECTING;//正在重连
        for(int i=0;i<_max_retries;i++)
        {
            Connect();
            if(_status==Status::CONNECTED)
            {
                return;
            }
            //重连时间间隔
            sleep(_retry_interval);
            std::cout<<"当前重连次数:"<<i+1<<",最大上限："<<_max_retries<<std::endl;
        }
        _status = Status::CLOSED;
    }

   
    void Process()
    {
        //和服务端通讯
        while(1)
        {
            std::string inbuffer;
            std::cout<<"Please Enter:";
            std::getline(std::cin,inbuffer);
            size_t n = write(_sockfd,inbuffer.c_str(),inbuffer.size());
            if(n>0)
            {
                char buffer[1024];
                size_t m = read(_sockfd,buffer,sizeof(buffer));
                if(m>0)
                {
                    buffer[m] = 0;
                    std::cout<<"Server Echo:"<<buffer<<std::endl;
                }
                else if(m==0)//服务端掉线了
                {
                    _status = Status::DISCONNECTED;
                    break;
                }
                else//出错了
                {
                    std::cout << "read m : " << m << "errno: " << errno << "errno string: " << strerror(errno) << std::endl;
                    _status = Status::CLOSED;
                    break;
                }
            }
             else//出错了
            {
                std::cout << "write n : " << n << "errno: " << errno << "errno string: " << strerror(errno) << std::endl;
                _status = Status::CLOSED;
                break;
            }
        }
        
    }


    Status GetStatus()
    {
        return _status;
    }

    ~ClientConnection()
    {
        DisConnect();
    }


private:
    int _sockfd;
    uint16_t _port;//端口号
    std::string _ip;//ip地址
    int _retry_interval;//重连的时间间隔
    int _max_retries;//最大重连次数
    Status _status;
    
};


class TcpClient
{
public:
    TcpClient(uint16_t port,const std::string& ip)
    :_conn(port,ip)
    {}
    void Excute()
    {
        while(1)
        {
            switch(_conn.GetStatus())
            {
                case Status::NEW:
                    _conn.Connect();
                    break;
                case Status::CONNECTED:
                    std::cout<<"已连接，准备通讯"<<std::endl;
                    _conn.Process();//和服务端进行通讯
                    break;
                case Status::DISCONNECTED:
                    std::cout<<"已断连，准备重连"<<std::endl;
                    _conn.ReConnect();//断线重连
                    break;
                case Status::CLOSED:
                    _conn.DisConnect();
                    std::cout<<"重连失败，准备退出"<<std::endl;
                    return;
                default:
                    return;
            }
        }
    }
private:
    ClientConnection _conn;
};


void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

int main(int argc,char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    TcpClient client(serverport, serverip);
    client.Excute();
    return 0;
    
    return 0;
}